package com.singfan.core.dao.database.config;

import com.singfan.common.SingFanException;
import com.singfan.common.db.*;
import com.singfan.common.util.StringUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 配置数据访问类
 * Author: hansonghe
 * Date: 2015-08-19 13:54
 * Desc:
 */
public class SingFanConfigDao extends DaoBase {
    private static SingFanConfigDao instance = new SingFanConfigDao();

    private SingFanConfigDao() {
    }

    /**
     * 获取配置数据接口
     *
     * @return 配置数据接口
     */
    public static SingFanConfigDao getInstance() {
        return instance;
    }

    /**
     * 获取一个实体bean对象列表
     *
     * @param tClass 实体bean对象的class信息
     * @param <T>    实体bean对象的类型
     * @return 实体bean对象列表
     */
    public <T> List<T> selectAll(final Class<T> tClass) {
        String tableName = StringUtil.javaName2CommonName(tClass.getSimpleName());
        String sql = "SELECT * FROM " + tableName;

        Object result = executeQuery(null, sql, null, new IResultSetReader() {
            @Override
            public Object readObject(ResultSet resultSet)  {
                try {
                    List<T> result = new ArrayList<>();
                    while(resultSet.next()){
                        T t = tClass.newInstance();
                        DbUtil.fillBean(t, resultSet);
                        result.add(t);
                    }
                    return result;
                }
                catch (Exception ex){
                    throw new RuntimeException("SingFanConfigDao.selectAll error: " + ex.getMessage(), ex);
                }
            }
        });

        return (List<T>)result;
    }

    public int createMasterShop(String masterShopName){
        String sql = "INSERT INTO master_shop_config (name) VALUES (?)";
        List<Object> params = new ArrayList<>(1);
        params.add(masterShopName);
        Object executeResult = executeWithResult(null, sql, params, new IStatementProcessor() {
            @Override
            public Object afterExecute(Statement statement) {
                try {
                    int autoIncrementKey = -1;
                    ResultSet resultSet = statement.getGeneratedKeys();
                    if (resultSet.next()) {
                        autoIncrementKey = resultSet.getInt(1);
                    }
                    resultSet.close();
                    return autoIncrementKey;
                } catch (SQLException ex) {
                    throw new RuntimeException("createMasterShop error: " + ex.getMessage(), ex);
                }
            }
        });

        return Integer.parseInt(executeResult.toString());
    }

    @Override
    protected String getDatabaseId(Object hashKey) {
        return DbContext.getDbConfigProvider().getConfigDatabaseId();
    }
}